package com.company.calendar.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.calendar.dto.HolidayDTO;
import com.company.calendar.entity.Company;
import com.company.calendar.entity.Holiday;
import com.company.calendar.entity.HolidayType;
import com.company.calendar.mapper.CompanyMapper;
import com.company.calendar.mapper.HolidayMapper;
import com.company.calendar.mapper.HolidayTypeMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 节假日服务类
 *
 * @author System
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class HolidayService {

    private final HolidayMapper holidayMapper;
    private final HolidayTypeMapper holidayTypeMapper;
    private final CompanyMapper companyMapper;

    /**
     * 创建节假日
     */
    public HolidayDTO createHoliday(HolidayDTO holidayDTO) {
        log.info("创建节假日: {}", holidayDTO.getHolidayName());

        // 验证公司是否存在
        Company company = companyMapper.selectById(holidayDTO.getCompanyId());
        if (company == null || company.getIsDeleted()) {
            throw new RuntimeException("公司不存在: " + holidayDTO.getCompanyId());
        }

        // 检查日期是否已存在节假日
        LambdaQueryWrapper<Holiday> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Holiday::getCompanyId, holidayDTO.getCompanyId())
                   .eq(Holiday::getHolidayDate, holidayDTO.getHolidayDate());

        if (holidayMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("该日期已存在节假日: " + holidayDTO.getHolidayDate());
        }

        // 验证节假日类型是否存在
        HolidayType holidayType = holidayTypeMapper.selectById(holidayDTO.getTypeId());
        if (holidayType == null || holidayType.getIsDeleted()) {
            throw new RuntimeException("节假日类型不存在: " + holidayDTO.getTypeId());
        }

        Holiday holiday = new Holiday();
        holiday.setCompanyId(holidayDTO.getCompanyId());
        holiday.setHolidayName(holidayDTO.getHolidayName());
        holiday.setHolidayDate(holidayDTO.getHolidayDate());
        holiday.setTypeId(holidayDTO.getTypeId());
        holiday.setIsWorkday(holidayDTO.getIsWorkday());
        holiday.setDescription(holidayDTO.getDescription());

        holidayMapper.insert(holiday);
        return convertToDTO(holiday, holidayType);
    }

    /**
     * 根据ID获取节假日信息
     */
    @Transactional(readOnly = true)
    public Optional<HolidayDTO> getHolidayById(Long id) {
        Holiday holiday = holidayMapper.selectById(id);
        if (holiday == null || holiday.getIsDeleted()) {
            return Optional.empty();
        }

        HolidayType holidayType = holidayTypeMapper.selectById(holiday.getTypeId());
        return Optional.of(convertToDTO(holiday, holidayType));
    }

    /**
     * 根据公司ID获取节假日列表
     */
    @Transactional(readOnly = true)
    public List<HolidayDTO> getHolidaysByCompanyId(Long companyId) {
        LambdaQueryWrapper<Holiday> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Holiday::getCompanyId, companyId)
                   .orderByAsc(Holiday::getHolidayDate);

        return holidayMapper.selectList(queryWrapper)
                .stream()
                .map(holiday -> {
                    HolidayType holidayType = holidayTypeMapper.selectById(holiday.getTypeId());
                    return convertToDTO(holiday, holidayType);
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据公司ID和年份获取节假日列表
     */
    @Transactional(readOnly = true)
    public List<HolidayDTO> getHolidaysByCompanyIdAndYear(Long companyId, Integer year) {
        return holidayMapper.findByCompanyIdAndYear(companyId, year)
                .stream()
                .map(holiday -> {
                    HolidayType holidayType = holidayTypeMapper.selectById(holiday.getTypeId());
                    return convertToDTO(holiday, holidayType);
                })
                .collect(Collectors.toList());
    }

    /**
     * 根据公司ID和日期范围获取节假日列表
     */
    @Transactional(readOnly = true)
    public List<HolidayDTO> getHolidaysByDateRange(Long companyId, LocalDate startDate, LocalDate endDate) {
        return holidayMapper.findByCompanyIdAndDateRange(companyId, startDate, endDate)
                .stream()
                .map(holiday -> {
                    HolidayType holidayType = holidayTypeMapper.selectById(holiday.getTypeId());
                    return convertToDTO(holiday, holidayType);
                })
                .collect(Collectors.toList());
    }

    /**
     * 更新节假日信息
     */
    public HolidayDTO updateHoliday(Long id, HolidayDTO holidayDTO) {
        log.info("更新节假日信息: {}", id);

        Holiday holiday = holidayMapper.selectById(id);
        if (holiday == null || holiday.getIsDeleted()) {
            throw new RuntimeException("节假日不存在: " + id);
        }

        // 验证公司是否存在
        Company company = companyMapper.selectById(holidayDTO.getCompanyId());
        if (company == null || company.getIsDeleted()) {
            throw new RuntimeException("公司不存在: " + holidayDTO.getCompanyId());
        }

        // 检查日期是否被其他节假日使用
        if (!holiday.getHolidayDate().equals(holidayDTO.getHolidayDate())) {
            LambdaQueryWrapper<Holiday> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Holiday::getCompanyId, holidayDTO.getCompanyId())
                       .eq(Holiday::getHolidayDate, holidayDTO.getHolidayDate())
                       .ne(Holiday::getId, id);

            if (holidayMapper.selectCount(queryWrapper) > 0) {
                throw new RuntimeException("该日期已存在节假日: " + holidayDTO.getHolidayDate());
            }
        }

        // 验证节假日类型是否存在
        HolidayType holidayType = holidayTypeMapper.selectById(holidayDTO.getTypeId());
        if (holidayType == null || holidayType.getIsDeleted()) {
            throw new RuntimeException("节假日类型不存在: " + holidayDTO.getTypeId());
        }

        holiday.setHolidayName(holidayDTO.getHolidayName());
        holiday.setHolidayDate(holidayDTO.getHolidayDate());
        holiday.setTypeId(holidayDTO.getTypeId());
        holiday.setIsWorkday(holidayDTO.getIsWorkday());
        holiday.setDescription(holidayDTO.getDescription());

        holidayMapper.updateById(holiday);
        return convertToDTO(holiday, holidayType);
    }

    /**
     * 删除节假日（软删除）
     */
    public void deleteHoliday(Long id) {
        log.info("删除节假日: {}", id);

        Holiday holiday = holidayMapper.selectById(id);
        if (holiday == null || holiday.getIsDeleted()) {
            throw new RuntimeException("节假日不存在: " + id);
        }

        holidayMapper.deleteById(id);
    }

    /**
     * 转换为DTO
     */
    private HolidayDTO convertToDTO(Holiday holiday, HolidayType holidayType) {
        HolidayDTO dto = new HolidayDTO();
        dto.setId(holiday.getId());
        dto.setCompanyId(holiday.getCompanyId());
        dto.setHolidayName(holiday.getHolidayName());
        dto.setHolidayDate(holiday.getHolidayDate());
        dto.setTypeId(holiday.getTypeId());
        dto.setIsWorkday(holiday.getIsWorkday());
        dto.setDescription(holiday.getDescription());

        if (holidayType != null) {
            dto.setTypeName(holidayType.getTypeName());
            dto.setTypeCode(holidayType.getTypeCode());
            dto.setTypeColor(holidayType.getColor());
        }

        return dto;
    }
}


